<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    搜索： <input type="text" id="search" />
  </body>
  <script>
    //函数防抖[func 函数,wait 延迟执行毫秒数,immediate true 表立即执行,false 表非立即执行,立即执行是触发事件后函数会立即执行，然后n秒内不触发事件才能继续执行函数的效果]
    const debounce = function (func, wait, immediate) {
      let timeout
      return function () {
        let context = this
        let args = arguments
        if (timeout) {
          clearTimeout(timeout)
        }
        if (immediate) {
          var callNow = !timeout
          console.log(callNow)
          timeout = setTimeout(() => {
            timeout = null
          }, wait)
          if (callNow) {
            func.apply(context, args)
          }
        } else {
          timeout = setTimeout(function () {
            func.apply(context, args)
          }, wait)
        }
      }
    }
    const search = document.getElementById('search')
    search.addEventListener(
      'keyup',
      debounce(
        function (e) {
          console.log(e.target.value) //请求ajax
        },
        1000,
        true
      )
    )
  </script>
</html>
